package com.wing.portal.aggregation.portletinfo;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.wing.cms.domain.Article;
import com.wing.cms.domain.Portlet;
import com.wing.cms.service.ArtgroupManager;
import com.wing.cms.service.ArticleManager;
import com.wing.cms.service.PortletManager;
import com.wing.common.util.ApplicationPath;
import com.wing.common.util.PageBean;
import com.wing.common.util.SpringDI;
@Service
public class ArticlePortletInfo implements PortletInfo {

	private List<Map<String, Object>> findArtgroupsByPid(String pid ,String siteId) {
		ArtgroupManager artgroupManager = (ArtgroupManager) SpringDI
				.getBean("artgroupManager");
		List<Map<String, Object>> artgroups = artgroupManager.findChildByID(pid, siteId);
		for (Map<String, Object> artgroup : artgroups) {
			setChild(artgroupManager,artgroup,siteId);
		}
		return artgroups;
	}

	private void setChild(ArtgroupManager artgroupManager,Map<String, Object> artgroup,String siteId) {
		String id = (String)artgroup.get("id");
		List<Map<String, Object>> artgroups = artgroupManager.findChildByID(id, siteId);
		for (Map<String, Object> artg : artgroups) {
			setChild(artgroupManager,artg,siteId);
		}
		artgroup.put("childList", artgroups);
	}
	/**
	 * 装载文章展现形式的设置信息
	 * 
	 * @param Map<String,String> param
	 * @return Map
	 */
	public Map loadPortletInfo(Map<String, String> param) {
		Map root = new HashMap();
		String portletId = param.get("portletid");
		String siteId = param.get("siteId");
		PortletManager portletInstanceManager = (PortletManager) SpringDI
				.getBean("portletManager");
		Portlet portletInfo = portletInstanceManager.findById(portletId);
		if(portletInfo==null){
			root.put("portletWidth", 40);
			root.put("portletheight", 10);
			return root;
		}
		int articleCount = portletInfo.getArticlecount();
		int titleLength = portletInfo.getTitlelength();
		int summaryLength = portletInfo.getSummarylength();
		int portletWidth = portletInfo.getPortletwidth();
		int portletheight = portletInfo.getPortletheight();
		String artgroupId = portletInfo.getArtgroupId();
		String isnavi = portletInfo.getIsnavi();
		root.put("title", portletInfo.getTitle());
		root.put("titlecolor", portletInfo.getTitlecolor());
		root.put("assoportlet", portletInfo.getAssoportlet());
		root.put("titletype", portletInfo.getTitletype()==null?"0":portletInfo.getTitletype());
		root.put("titlepic", portletInfo.getTitlepic());
		if(Portlet.ISNAVI_TRUE.equals(isnavi)){
			List<Map<String, Object>> artgroups = findArtgroupsByPid(artgroupId,siteId);
			root.put("artgroups",artgroups);
		}else{
			ArticleManager articleManager = (ArticleManager) SpringDI
				.getBean("articleManager");
			PageBean articleList = articleManager.findByGroupId(1, 50, artgroupId,
					null);
	
			// List<CmsChannel> childrenPageList =
			// channelManager.getChildrenChannels(channelId);
	
			String webapp = ApplicationPath.getParameter("webapp");
			// String lafPath = portletInstanceManager
			// .findLookAndFeelPathByPageId(this.getId().split("&")[1]);
			String lafPath = "";
			String realLafPath = "framework/skins/" + lafPath + "/images/";
	
			// root.put("childrenPageList", childrenPageList);
			// 处理文章列表
			List<Article> showArticleList = new ArrayList();
			int count = 0;
			for (int i = 0; i < articleList.getRecordList().size(); i++) {
				Map<String, Object> dataMap = articleList.getRecordList().get(i);
				Article tempArticle = new Article();
				tempArticle.setId((String) dataMap.get("id"));
				// 设置展示题目
				String title = (String) dataMap.get("art_name");
				double titleLengthFlag = 0;
				StringBuffer sb = new StringBuffer();
				String showTitle = title;
				if (title.getBytes().length > titleLength * 2) {
					for (int a = 0; a < title.length(); a++) {
						char c = title.charAt(a);
						if (String.valueOf(c).getBytes().length == 2) {
							titleLengthFlag += 1;
						} else {
							titleLengthFlag += 0.5;
						}
						sb.append(c);
						if (titleLengthFlag >= titleLength)
							break;
	
					}
					showTitle = sb.toString() + "...";
				}
				tempArticle.setArt_name(title);
				tempArticle.setShowTitle(showTitle);
				// 设置文章摘要
				String summary = "";
				if ((String) dataMap.get("summary") != null
						&& !"".equals((String) dataMap.get("summary"))) {
					summary = (String) dataMap.get("summary");
				}
				String showSummary = summary;
				if (summary.length() > summaryLength) {
					showSummary = summary.substring(0, summaryLength) + "...";
				}
				tempArticle.setSummary(showSummary);
				// 设置文章时间
				Date date = new Date();
				date.setTime(((Timestamp) dataMap.get("create_time")).getTime());
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				String createtimeSrc = df.format(date);
				tempArticle.setReatetimeSrc(createtimeSrc);
				// 设置文章内容
				String content = "";
				try {
					content = articleManager.findContentById((String) dataMap
							.get("id"));
				} catch (IOException e) {
					e.printStackTrace();
				}
				String imgSrc = this.parsingImgUrl(content);
				tempArticle.setFirtImgrSrc(imgSrc);
				tempArticle.setContent(content);
				// 设置链接路径
				count++;
				if (count > articleCount)
					break;
				showArticleList.add(tempArticle);
			}
	
			// String cssPath = "framework/skins/" + lafPath + "/css/";
			//		
			// String imgPath = "framework/skins/" + lafPath + "/images/";
	
			if (showArticleList.size() == 0) {
				root.put("haveArticles", "none");
			} else {
				root.put("haveArticles", "many");
				Article[] articles = new Article[showArticleList.size()];
				showArticleList.toArray(articles);
				root.put("articles", articles);
				root.put("article", showArticleList.get(0));
			}
			if (articleList.getRecordList().size() > articleCount) {
				root.put("more", "more");
			} else {
				root.put("more", "none");
			}
			// root.put("cssPath", cssPath);
			// root.put("imgPath", imgPath);
			// root.put("channelId", pageId);
		}
		root.put("cssPath", "");
		root.put("imgPath", "");
		root.put("channelId", "");
		root.put("artgroupId", artgroupId);
		root.put("portletWidth", portletWidth);
		root.put("portletheight", portletheight);
		return root;
	}

	/**
	 * 通过portletId查找模板位置
	 * 
	 * @param portletId 
	 * @return 
	 */
	public String findTemplateFile(String portletId) {
		PortletManager portletInstanceManager = (PortletManager) SpringDI
				.getBean("portletManager");
		return portletInstanceManager.findTemplateFile(portletId);
	}
	
	/**
	 * 解析文章中第一张图片路径
	 * 
	 * @param content
	 * @return
	 */
	public static String parsingImgUrl(String content) {
		String[] photoTypes = { "jpg", "JPG", "bmp", "BMP", "gif", "GIF",
				"jpeg", "JPEG","png","PNG" };
		String url = "";
		int begin = content.indexOf("<img");
		int begin1 = content.indexOf("<IMG");
		if (begin1 > begin) {
			begin = begin1;
		}
		int end = 0;
		if (begin < 0) {
			url = "/resources/images/error.gif";
		} else {
			url = content.substring(begin);
			int e = url.indexOf("</img>");
			int e1 = url.indexOf("</IMG>");
			int e2 = url.indexOf("/>");
			int e3 = url.indexOf(">");
			if (e==-1 || (e1!=-1 && e1<e)) {
				e=e1;
			}
			if (e==-1 || (e2!=-1 && e2<e)) {
				e=e2;
			}
			if (e==-1 || (e3!=-1 && e3<e)) {
				e=e3;
			}
			url = url.substring(0,e);
			for (int k = 0; k < photoTypes.length; k++) {
				end = url.indexOf(photoTypes[k]);
				if (end != -1)
					break;
			}
			if(end == -1){
				return url;
			}
			// url = content.substring(begin, end + 4);
			int begin2 = url.indexOf("src=");
			if (url.indexOf("SRC=") > begin2) {
				begin2 = url.indexOf("SRC=");
			}
			url = url.substring(begin2 + 5, end + 3);
		}
		return url;
	}

}
